package com.mr.web.support;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.map.UnmodifiableMap;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;

import com.mr.model.Config;


public class VelocityTemplate {
	protected static org.apache.log4j.Logger log = org.apache.log4j.Logger
			.getLogger(VelocityTemplate.class);
	private VelocityEngine velocityEngine;
	private Map velocityTools;

	public void setVelocityEngine(VelocityEngine velocityEngine) {
		this.velocityEngine = velocityEngine;
	}

	public VelocityEngine getVelocityEngine() {
		return velocityEngine;
	}

	public VelocityTemplate() {
		Map tools = new HashMap();
		tools.put("basePath", Config.PROJECT_NAME);
		velocityTools = UnmodifiableMap.decorate(tools);
	}

	public String parseTemplate(String template, Map model) {
		model.putAll(velocityTools);
		Context context = new VelocityContext(model);
		Writer writer = new StringWriter();
		try {
			velocityEngine.mergeTemplate(template, "UTF-8", context, writer);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return writer.toString();
	}

	public void parseTemplate(String template, Map model, Writer writer) {
		model.putAll(velocityTools);
		Context context = new VelocityContext(model);
		try {
			velocityEngine.mergeTemplate(template, "UTF-8", context, writer);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void parseTemplate(String template, Map model, OutputStream os) {
		model.putAll(velocityTools);
		Context context = new VelocityContext(model);
		Writer writer = new OutputStreamWriter(os);
		try {
			velocityEngine.mergeTemplate(template, "UTF-8", context, writer);
		} catch (Exception e) {
			log.warn("", e);
		}
	}
}
